package com.jdk.demo.io;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class CloseDemo {

	// 调用Stream的close方法造成Socket关闭
	public static void main(String[] args) {
		try {
			byte[] charArray = new byte[10];
			ServerSocket serverSocket = new ServerSocket(8088);
			Socket socket = serverSocket.accept();

			InputStream inputStream = socket.getInputStream();
			int readLength = inputStream.read(charArray);
			// 只有在对端调用了outputStream.close方法后，代表到达流的结尾，不再传输数据了(readLength != -1)
			while(readLength != -1) {
				String newString = new String(charArray, 0, readLength);
				System.out.println(newString + " " + System.currentTimeMillis());
				readLength = inputStream.read(charArray);
			}
			inputStream.close();
			// 会抛出异常，因为Stream在Socket技术中进行应用时，如果关闭返回的stream，将关闭关联的Socket，类型为InputStream的对象inputStream的真正数据类型是SocketInputStream
			// 从源码上看，当调用SocketInputStream的close方法时，顺便也将Socket关闭了
			/**
			 * public void close() throws IOException {
			        if (closing)
			            return;
			        closing = true;
			        if (socket != null) {
			            if (!socket.isClosed())
			                socket.close();
			        } else
			            impl.close();
			        closing = false;
			    }
			 * */
			// OutputStream outputStream = socket.getOutputStream();
			socket.close();
			serverSocket.close();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}

}
